package com.atguigu.gmall.cart.interceptors;

import com.atguigu.core.utils.CookieUtils;
import com.atguigu.core.utils.JwtUtils;
import com.atguigu.gmall.cart.config.JwtProperties;
import com.atguigu.gmall.cart.pojo.UserInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.UUID;

/**
 * 自定义拦截器
 */
@Component
@EnableConfigurationProperties(JwtProperties.class)
public class LoginInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private JwtProperties jwtProperties;

    private static final ThreadLocal<UserInfo> THREAD_LOCAL = new ThreadLocal<>();
    /**
     * 目的不是拦截，是统一获取登录状态的
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    //前置拦截器，在请求CartController里面的方法时，会执行这个方法，去执行拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //用于参数的传递
        UserInfo userInfo=new UserInfo();

        //1、获取cookie中的token信息（jwt)及user-key
        String token = CookieUtils.getCookieValue(request, this.jwtProperties.getCookieName());
        String userKey = CookieUtils.getCookieValue(request, this.jwtProperties.getUserKey());
        //2、判断有没有user-key,没有的话制作一个放入cookie
        if(StringUtils.isEmpty(userKey)){
            userKey= UUID.randomUUID().toString();
            CookieUtils.setCookie(request,response,this.jwtProperties.getUserKey(),userKey,this.jwtProperties.getExpire());
        }

        // 不管有没有登录都要设置userKey
        userInfo.setUserKey(userKey);

        //3、判断有没有token
        if(StringUtils.isNotBlank(token)){
            //4、解析token信息
            Map<String, Object> infoFromToken = JwtUtils.getInfoFromToken(token, this.jwtProperties.getPublicKey());

            if(!CollectionUtils.isEmpty(infoFromToken)){
                userInfo.setId(new Long(infoFromToken.get("id").toString()));
            }
        }

        // 保存到threadlocal
        THREAD_LOCAL.set(userInfo);//key会主动放入，只需要放入value

        return super.preHandle(request, response, handler);
    }


    //获取
    public static UserInfo getUserInfo(){
        return THREAD_LOCAL.get();
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //必须手动清除ThreadLocal中的线程变量，因为使用的是Tomcat线程池，否则会出现内存泄漏
        THREAD_LOCAL.remove();
    }

}
